package com.mldong.modules.sys.tasks;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.mldong.modules.sys.api.TaskExecutionApi;
import com.mldong.modules.sys.dto.TaskExecutionQueueDTO;
import com.mldong.modules.sys.entity.ThirdPartyCallback;
import com.mldong.modules.sys.enums.ThirdPartyCallbackHandleStatusEnum;
import com.mldong.modules.sys.service.ThirdPartyCallbackService;
import com.mldong.tasks.AbstractTaskExecutionTaskRunner;
import com.mldong.timer.TaskExecutor;
import org.springframework.stereotype.Component;

import java.util.List;

/***
 * 第三方回调任务执行器 and 第三方回调补偿任务
 * @author mldong
 */
@Component
public class ThirdPartyCallbackTaskRunner extends AbstractTaskExecutionTaskRunner implements TaskExecutor {

    public ThirdPartyCallbackTaskRunner(TaskExecutionApi taskExecutionApi) {
        super(taskExecutionApi);
    }

    @Override
    protected List<TaskExecutionQueueDTO> getPendingTasks() {
        return super.taskExecutionApi.getPendingTasks(this.getClass(), 100);
    }

    @Override
    public String getCron() {
        // 每3分钟执行一次
        return "0 0/3 * * * ?";
    }

    @Override
    public boolean isXxlJob() {
        return false;
    }

    @Override
    public String getName() {
        return "第三方回调补偿任务";
    }

    @Override
    public boolean execute(Long bizId, Dict ext) {
        ThirdPartyCallbackService thirdPartyCallbackService = SpringUtil.getBean(ThirdPartyCallbackService.class);
        ThirdPartyCallback thirdPartyCallback = thirdPartyCallbackService.findById(bizId);

        if (thirdPartyCallback == null ||
                ThirdPartyCallbackHandleStatusEnum.SUCCESS.getCode().equals(thirdPartyCallback.getHandleStatus())) {
            return true;
        }

        String handleResult = thirdPartyCallbackService.handle(thirdPartyCallback, false);
        return ObjectUtil.equals(handleResult, "SUCCESS");
    }
}
